package com.punegtug.opensocial.gifts.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.punegtug.opensocial.gifts.model.Gift;
import com.punegtug.opensocial.gifts.model.GiftTransaction;
import com.punegtug.opensocial.gifts.persistence.PMF;

@SuppressWarnings("serial")
public class GiftsTransactionServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		
		String receiverId = req.getParameter("receiver_id");
		String senderId = req.getParameter("sender_id");
		String giftKey = req.getParameter("gift_key");
		
		if(receiverId!=null&& receiverId.trim().length()>0 && senderId!=null && senderId.trim().length()>0 && giftKey!=null && giftKey.trim().length()>0){
			PersistenceManager pMgr = PMF.get().getPersistenceManager();
			GiftTransaction giftTxn=new GiftTransaction(giftKey,receiverId,senderId);
			pMgr.makePersistent(giftTxn);
		}
		
		
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("application/json");
		String receiverId = req.getParameter("receiver_id");
		String senderId = req.getParameter("sender_id");
		PersistenceManager pMgr = PMF.get().getPersistenceManager();

		List<GiftTransaction> giftsTxns = null;
		if (receiverId != null) {
			Query query = pMgr.newQuery(GiftTransaction.class);
			query.setFilter("receiverId == receiverIdNameParam");
			query.declareParameters("String receiverIdNameParam");
			giftsTxns=(List<GiftTransaction>) query.execute(receiverId);
		}

		else if (senderId != null) {
			Query query = pMgr.newQuery(GiftTransaction.class);
			query.setFilter("senderId == senderIdNameParam");
			query.declareParameters("String senderIdNameParam");
			giftsTxns=(List<GiftTransaction>) query.execute(senderId);

		} 
		
		StringBuilder strBuilder = new StringBuilder("[");
		int count=0;
		for (GiftTransaction giftTxn : giftsTxns) {
			if(count>0){
				strBuilder.append(",");
			}
			strBuilder.append("{");
			strBuilder.append("\"sender_id\":\"").append(giftTxn.getSenderId()).append("\"");
			strBuilder.append(",");
			strBuilder.append("\"receiver_id\":\"").append(giftTxn.getReceiverId()).append("\"");
			strBuilder.append(",");
			strBuilder.append("\"gift_key\":\"").append(giftTxn.getGiftKey()).append("\"");
			strBuilder.append("}");
			count++;
		}
		strBuilder.append("]");
		resp.getWriter().println(strBuilder.toString());
	}
}
